package cn.big.netty.learn.echo.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * Created by LiJianXin on 2019/5/8 0008.
 */
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {


	/**
	 * 每当从客户端接收到新数据时，都会使用接收到的消息调用此方法
	 *
	 * @param ctx
	 * @param msg 接收到的消息类型为ByteBuf.
	 * @throws Exception
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println(((ByteBuf) msg).toString(CharsetUtil.UTF_8));
		ctx.write(msg);
//		ctx.flush();
		//可以这样写
//		ctx.writeAndFlush(msg);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		//关闭通道后，冲刷所有消息到远程节点。
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		//关闭通道
		ctx.close();
	}
}
